﻿using Newtonsoft.Json;
using QWManage.API.CustomerDetailB92994;
using QWManage.API.TagMgr92118;
using QWManage.Model;
using QWManage.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace QWManage.Forms
{
    public partial class FrmTags : Form
    {
        private Thread _thread;
        private List<TagInfo> _sysTags = new List<TagInfo>();
        private Dictionary<string, int> _tagID2TotalDic = new Dictionary<string, int>();
        private Dictionary<string, string> _tagID2NameDic = new Dictionary<string, string>();
        public FrmTags()
        {
            InitializeComponent();
        }



        private int iOld = -1;
        private void g_loadUIDlistView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (lvTags.SelectedIndices.Count > 0) //若有选中项 
            {
                if (iOld == -1)
                {
                    lvTags.Items[lvTags.SelectedIndices[0]].BackColor = SystemColors.Highlight; //设置选中项的背景颜色 
                    lvTags.Items[lvTags.SelectedIndices[0]].ForeColor = Color.White;
                    iOld = lvTags.SelectedIndices[0]; //设置当前选中项索引 
                }
                else
                {
                    if (lvTags.SelectedIndices[0] != iOld)
                    {
                        lvTags.Items[lvTags.SelectedIndices[0]].BackColor = SystemColors.Highlight; //设置选中项的背景颜色 
                        lvTags.Items[iOld].BackColor = SystemColors.Window;//恢复默认背景色 
                        lvTags.Items[iOld].ForeColor = Color.Black;

                        iOld = lvTags.SelectedIndices[0]; //设置当前选中项索引 
                    }
                }
            }
            else //若无选中项 
            {
                lvTags.Items[iOld].BackColor = SystemColors.Window;//恢复默认背景色 
                lvTags.Items[iOld].ForeColor = Color.Black;
                iOld = -1; //设置当前处于无选中项状态 
            }
        }

        private void FrmTags_Load(object sender, EventArgs e)
        {
            lvTags.View = View.Details;
            lvTags.FullRowSelect = true;
            lvTags.MultiSelect = false;
            lvTags.HideSelection = true;
            this.lvTags.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(this.g_loadUIDlistView_ItemSelectionChanged);

            lvTags.Columns.Add(new ColumnHeader() { Text = "标签", Width = lvTags.Width / 2 - 1 });
            lvTags.Columns.Add(new ColumnHeader() { Text = "数量", Width = lvTags.Width / 2 - 1 });

            cmbBatchCount.Items.Add("全部");
            cmbBatchCount.Items.Add("20");
            cmbBatchCount.Items.Add("50");
            cmbBatchCount.Items.Add("100");
            cmbBatchCount.Items.Add("200");
            cmbBatchCount.Items.Add("500");
            cmbBatchCount.SelectedIndex = 0;
            cmbBatchCount.DropDownStyle = ComboBoxStyle.DropDownList;

            lblCurrentUser.Text = "     ";
            lblCurrentUser.ForeColor = Color.Red;

            this.FormClosing += FrmTags_FormClosing;

            string tokenA = API.AccessToken.TokenA.GetAccessToken();
            //获取企业标签库  密码用这个 a_nrmHsQtURZNKLKxMGkFTeHLFXpnN6TPd8-lz7xhHM
            API.TagLibrary92117.TagLibraryArgs tagLibraryArgs = new API.TagLibrary92117.TagLibraryArgs();
            tagLibraryArgs.group_id = null;
            tagLibraryArgs.tag_id = null;
            _sysTags = API.TagLibrary92117.TagLibraryAPI.Invoke(tokenA, tagLibraryArgs);

            List<TagInfo> tagsDel = new List<TagInfo> { new TagInfo() { ID = "", Name = "" } };
            List<TagInfo> tagsAdd = new List<TagInfo> { new TagInfo() { ID = "", Name = "" } };

            foreach (TagInfo tagInfo in _sysTags)
            {
                tagsDel.Add(tagInfo);
                tagsAdd.Add(tagInfo);
            }
            if (cmbDelTags.DataSource != null)
                cmbDelTags.DataSource = null;

            cmbDelTags.Items.Clear();
            cmbDelTags.DataSource = tagsDel;
            cmbDelTags.DisplayMember = "Name";
            cmbDelTags.ValueMember = "ID";
            cmbDelTags.DropDownStyle = ComboBoxStyle.DropDownList;

            if (cmbAddTags.DataSource != null)
                cmbAddTags.DataSource = null;

            cmbAddTags.Items.Clear();
            cmbAddTags.DataSource = tagsAdd;
            cmbAddTags.DisplayMember = "Name";
            cmbAddTags.ValueMember = "ID";
            cmbAddTags.DropDownStyle = ComboBoxStyle.DropDownList;

        }

        private void FrmTags_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null && _thread.IsAlive) _thread.Abort();
        }

        private void btnGetUser_Click(object sender, EventArgs e)
        {
            FrmGetUser frm = new FrmGetUser();
            if (frm.ShowDialog() != DialogResult.OK) return;
            lvTags.Items.Clear();
            lblCurrentUser.Text = frm.User.Name;
            lblCurrentUser.Tag = frm.User;
            _thread = new Thread(new ThreadStart(workService));
            _thread.Start();
        }

        private void workService()
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                progressBar.Enabled = true;

                _tagID2NameDic.Clear();
                _tagID2TotalDic.Clear();

                UserInfo userInfo = lblCurrentUser.Tag as UserInfo;
                //获取Token
                string tokenA = API.AccessToken.TokenA.GetAccessToken();

                _tagID2TotalDic = new Dictionary<string, int>();
                foreach (TagInfo tagInfo in _sysTags)
                {
                    _tagID2NameDic.Add(tagInfo.ID, tagInfo.Name);
                    _tagID2TotalDic.Add(tagInfo.ID, 0);
                }

                CustomerDetailBArgs args = new CustomerDetailBArgs();
                args.userid_list = new string[] { userInfo.UserID };
                args.limit = 100;
                args.cursor = "";
                List<CustomerTagInfo> customerTagInfos = CustomerDetailBAPI.InvokeTag(tokenA, args);
                saveCustomerTagInfosAsFile(customerTagInfos);
                foreach (CustomerTagInfo customer in customerTagInfos)
                {
                    if (customer.TagIds == null) continue;
                    if (customer.TagIds.Count == 0) continue;
                    foreach (string tagId in customer.TagIds)
                    {
                        if (!_tagID2TotalDic.ContainsKey(tagId)) { _tagID2TotalDic.Add(tagId, 0); }
                        _tagID2TotalDic[tagId]++;
                    }
                }
                display2ListView();
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }
        private void display2ListView()
        {
            lvTags.Items.Clear();
            foreach (TagInfo tagInfo in _sysTags)
            {
                ListViewItem lvItem = new ListViewItem();
                lvItem.Tag = tagInfo;
                lvItem.Text = tagInfo.Name;
                if (_tagID2TotalDic.ContainsKey(tagInfo.ID))
                {
                    lvItem.SubItems.Add(_tagID2TotalDic[tagInfo.ID].ToString());
                }
                else
                    lvItem.SubItems.Add("0");
                lvTags.Items.Add(lvItem);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            UserInfo userInfo = lblCurrentUser.Tag as UserInfo;
            if (userInfo == null)
            {
                Common.MessageBoxWarning("请先选择某个用户。");
                return;
            }
            lvTags.Items.Clear();
            _thread = new Thread(new ThreadStart(workService));
            _thread.Start();
        }

        private void btnEditTags_Click(object sender, EventArgs e)
        {
            if (lvTags.SelectedItems.Count == 0)
            {
                Common.MessageBoxWarning("请在左边先选择一个要操作的标签。");
                return;
            }
            if (cmbAddTags.SelectedIndex == 0 && cmbDelTags.SelectedIndex == 0)
            {
                Common.MessageBoxWarning("添加或移出标签不能同时为空。");
                return;
            }
            UserInfo userInfo = lblCurrentUser.Tag as UserInfo;
            if (userInfo == null)
            {
                Common.MessageBoxWarning("请先选择某个用户。");
                return;
            }
            _thread = new Thread(new ThreadStart(editTagsService));
            _thread.Start();
        }

        private void editTagsService()
        {
            try
            {
                int? count = null;
                if (cmbBatchCount.Text != "全部")
                    count = int.Parse(cmbBatchCount.Text);

                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                progressBar.Enabled = true;
                //获取Token
                string tokenA = API.AccessToken.TokenA.GetAccessToken();
                UserInfo userInfo = lblCurrentUser.Tag as UserInfo;
                TagInfo selectedTagInfo = lvTags.SelectedItems[0].Tag as TagInfo;
                string[] lines = getBatch(selectedTagInfo.ID, count);

                progressBar.Value = 0;
                progressBar.Minimum = 0;
                progressBar.Maximum = lines.Length;

                foreach (string line in lines)
                {
                    string customerID = line.Trim();
                    progressBar.Value++;
                    if (customerID == "") continue;

                    //编辑客户企业标签
                    TagMgrArgs makeTagArgs = new TagMgrArgs();
                    makeTagArgs.userid = userInfo.UserID;
                    makeTagArgs.external_userid = customerID;
                    //删除标签
                    //et2rMqDAAAoVZL3EYPAahbZBDfisCT4Q,一般
                    makeTagArgs.remove_tag = getSelectedTagIds(cmbDelTags);
                    //添加标签
                    //et2rMqDAAAR0p2uYl - XW2QAIPJ_14duA,重要
                    //et2rMqDAAAmwnBBfie5ICmFwswV5Z3VA, 核心
                    makeTagArgs.add_tag = getSelectedTagIds(cmbAddTags);
                    bool result = TagMgrAPI.Invoke(tokenA, makeTagArgs);
                    if (!result) throw new Exception("修改失败：TagMgrAPI.Invoke" + line);
                }
                //修改后自刷新
                workService();
                MessageBox.Show("修改完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }
        private static string[] getSelectedTagIds(ComboBox comboBox)
        {
            List<string> list = new List<string>();
            if (comboBox.SelectedIndex != 0)
            {
                list.Add((comboBox.SelectedItem as TagInfo).ID);
            }
            return list.ToArray();
        }

        private string[] getBatch(string tagId, int? count)
        {
            string fn = Path.Combine(Application.StartupPath, "CustomerTagInfos_TEMP_JSON.txt");
            if (!File.Exists(fn)) return new string[0];
            string json = File.ReadAllText(fn, Encoding.UTF8);
            List<CustomerTagInfo> list = JsonConvert.DeserializeObject<List<CustomerTagInfo>>(json);
            int num = count.HasValue ? count.Value : list.Count;
            if (num > list.Count) num = list.Count;
            List<string> ids = new List<string>();
            foreach (CustomerTagInfo taginfo in list)
            {
                if (taginfo.TagIds.Contains(tagId))
                    ids.Add(taginfo.ID);
                if (num == ids.Count) break;
            }
            return ids.ToArray();
        }

        private void saveCustomerTagInfosAsFile(List<CustomerTagInfo> customerTagInfos)
        {
            string fn = Path.Combine(Application.StartupPath, "CustomerTagInfos_TEMP_JSON.txt");
            string json = JsonConvert.SerializeObject(customerTagInfos);
            File.WriteAllText(fn, json, Encoding.UTF8);
        }
    }
}
